package com.spring.cloud.test.ribbon;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;

import java.io.PipedReader;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  自定义负载规则
 * </p>
 *
 * @author zql
 * @date 2018/5/17 15:30
 */
public class MyRule implements IRule{

    private ILoadBalancer lb;

    @Override
    public Server choose(Object o) {
        System.out.println("自定义规则 ");
        Random r = new Random();
        int rNum = r.nextInt(10);
        List<Server> servers = lb.getAllServers();

        if(rNum > 7){
            return getServerByPort(servers, 8762);
        }
        return getServerByPort(servers, 8763);
    }

    private Server getServerByPort(List<Server> servers, int port){
        for(Server s: servers){
            if(s.getPort() == port){
                return s;
            }
        }
        return null;
    }


    @Override
    public void setLoadBalancer(ILoadBalancer iLoadBalancer) {
        this.lb = iLoadBalancer;
    }

    @Override
    public ILoadBalancer getLoadBalancer() {
        return this.lb;
    }
}
